package com.xixing.weixin.domain;

import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;

import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = "findAccountsByWeixinCodeAndAccountType")
public class Account {

    public static final String GZHU_SCHOOL = "GZHU_SCHOOL";
    public static final String GZHU_LIBRARY = "GZHU_LIBRARY";

    @NotNull
    private String weixinCode;

    @NotNull
    private String studentCode;

    @NotNull
    private String studentPassword;

    @ManyToOne
    private School school;

    private Integer startYear;

    private String accountType;


    public int findYear() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        if (1 == findTerm())
            return year - startYear + 1;
        else
            return year - startYear;
    }

    public int findTerm() {
        Calendar calendar = Calendar.getInstance();
        int m = calendar.get(Calendar.MONTH);
        return (m < Calendar.AUGUST) ? 2 : 1;
    }

    public String findScoreYear(int year) {
        if (year <= 0) {
            year = findYear();
        }

        return findStudentYear(startYear, year);
    }

    public static String findStudentYear(int startYear, int year) {
        int end = startYear + year;
        int start = end - 1;
        return start + "-" + end;
    }


    public Integer getStartYear() {
        if(startYear == null) {
            if(GZHU_SCHOOL.equals(accountType)) {
                return Integer.parseInt("20" + studentCode.substring(0, 2));
            }
        }
        return this.startYear;
    }

    @Transactional
    public static void persistByWeixin(String weixinCode,String accountType,String studentCode,String studentPassword){
        Account account = new Account();
        account.setWeixinCode(weixinCode);
        account.setStudentCode(studentCode);
        account.setStudentPassword(studentPassword);
        account.setAccountType(accountType);
        //只有广大校务才这样.
        if(GZHU_SCHOOL.equals(accountType)){
            account.setStartYear(new Integer("20"+studentCode.substring(0,2)));  //取学号前两位
        }
//        account.setSchool(School.findSchoolsByWeixinCode(weixin.getToUserName()).getSingleResult());
        account.persist();
    }
}
